import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 60000 // 请求超时时间
})


function tips(status, data) {
  let title = ''
  let desc = ''
  switch (status){
    case 401:
      title = '未登录'
      desc = data.message
      store.dispatch('Logout').then(r => {})
      break;
    case 403:
      title = '禁止访问'
      desc = data.message
      break;
    case 422:
      title = '参数错误'
      desc = data[0].message
      break;
    default :
      title = '遇到错误'
      desc = data.message
      break
  }

  notification.error({
    message: title,
    description: desc
  })
}

// 异常拦截处理器
const errorHandler = (error) => {

  let data = error.response.data

  if (error.request.responseType === 'blob') {
    let reader = new FileReader()
    reader.readAsText(error.response.data, 'utf-8')
    data = reader.onload = res => {
      const { result } = res.target
      data = JSON.parse(result)
      tips(error.response.status, data)
    }
  } else {
    tips(error.response.status, data)
  }


  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }

  if (config.method.toLocaleLowerCase() === 'get') {
    config['params'] = config.data
  }

  if (config.method.toLocaleLowerCase() === 'put') {
    config['data'] = config.data
  }

  if (config.method.toLocaleLowerCase() === 'post') {
    config['data'] = config.data
  }

  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  return response.data
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
